<%@page import="es.usj.tac.meteorologica.dto.Weather"%>
<%@page import="es.usj.tac.meteorologica.controller.XMLParser"%>
<%@page import="es.usj.tac.meteorologica.dto.City"%>
<%@page import="es.usj.tac.meteorologica.dao.DAOFactory"%>
<%@page import="es.usj.tac.meteorologica.dto.Country"%>
<%@page import="java.net.URL"%>
<%@page import="java.net.MalformedURLException"%>
<%@page import="org.apache.axis.AxisFault"%>
<%@page import="NET.webserviceX.www.GlobalWeatherSoapStub"%>
<%@page import="NET.webserviceX.www.GlobalWeatherLocator"%>
<%@page import="NET.webserviceX.www.GlobalWeatherSoap"%>
<%@page import="NET.webserviceX.www.GlobalWeather"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% 
XMLParser xmlParser = new XMLParser();

try {
	GlobalWeather weatherClient = new GlobalWeatherLocator();
	GlobalWeatherSoap wsClient = new GlobalWeatherSoapStub(new URL(weatherClient.getGlobalWeatherSoapAddress()),weatherClient);
// 	String citiesResult = wsClient.getCitiesByCountry("Spain");
	List<Country> countries = DAOFactory.getInstance().getCountryDAO().listAll();
	for(Country country: countries){
		String citiesResult = wsClient.getCitiesByCountry(country.getName());
		List<City> citiesArray = xmlParser.readXMLCities(citiesResult);
		for(City city: citiesArray){
			if(DAOFactory.getInstance().getCityDAO().readByName(city.getName()) == null) 
				DAOFactory.getInstance().getCityDAO().create(city);
// 			out.print("Creado en BBDD: "+city.toString()+"--");
 			String xml =wsClient.getWeather(city.getName(), country.getName());
// 		String xml =wsClient.getWeather("Fuerteventura / Aeropuerto", "Spain");
			if(!xml.contains("Data Not Found")){
 				xml=xml.replaceAll("encoding=\"utf-16\"", "encoding=\"utf-8\"");
 				Weather weather = xmlParser.readXMLWeather(xml);
 				
				if(weather != null){
 					DAOFactory.getInstance().getWeatherDAO().create(weather);
					out.print("Weather="+weather.toString());
					out.print("<br/>");
				}else{
					out.print("weather nulo");
				}
			}
		}
	}
} catch (AxisFault e) {
	
	e.printStackTrace();
} catch (MalformedURLException e) {
	e.printStackTrace();
}
%>
</body>
</html>